package com.example.myproject.ratelimiter;

import com.google.common.util.concurrent.RateLimiter;
import org.joda.time.LocalDateTime;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RatelimiterDemo {
	public static void main(String[] args) {
		//0.5代表一秒最多多少个 代表2s 中出一个请求
		System.out.println(LocalDateTime.now().toDate());

		RateLimiter rateLimiter = RateLimiter.create(1);
		List<Runnable> tasks = new ArrayList<Runnable>();
		for (int i = 0; i < 10; i++) {
			tasks.add(new UserRequest(i));
		}
		ExecutorService threadPool = Executors.newCachedThreadPool();
		for (Runnable runnable : tasks) {
			System.out.println(new Date().toString()+",等待时间：" + rateLimiter.acquire());
			threadPool.execute(runnable);
		}
	}

	private static class UserRequest implements Runnable {
		private int id;

		public UserRequest(int id) {
			this.id = id;
		}

		public void run() {
			System.out.println("id:"+id);
		}
	}


}
